package cpa.prowon.gui.actions;

import java.util.Collection;

import pho.prowon.category.RootIndexCategory;
import cpa.prowon.gui.MainWindow;
import cpa.prowon.gui.MultiImageInformationWindow;
import cpa.prowon.gui.SingleImageInformationWindow;
import cpa.prowon.image.ImageContainer;

/**
 * This action is used to import images into the image. The class is abstract to provide
 * common import functionality but has to be subclassed in order to provide functionality
 * to get the images that shall be imported
 * @author Chris
 */
abstract class ImportAction extends PatchedAction {

	// The methods that have to be ipmlemented in the sub classes
	abstract protected Collection getImagesToImport();
	
	/**
	 * Constructor
	 * @param MainWindow The window where the application is used
	 * @author Chris
	 */
	public ImportAction(MainWindow w) {
		super(w);
	}
	
	/**
	 * Run the action
	 * @author Chris
	 */
	public void run() {

		// Get the image names
		Collection imageList = getImagesToImport();
		
		// Return if no images were returned
		if (imageList.size() == 0) return;

		// Set the image information
		try
		{
			
			// Convert the collection to a simple array
			ImageContainer[] imageContainerList = (ImageContainer[]) imageList.toArray(new ImageContainer[imageList.size()]);

			// Open the image window to set some basic information
			if (imageContainerList.length == 1) {
				SingleImageInformationWindow iw = new SingleImageInformationWindow(window, imageContainerList[0]);
				iw.open(!imageContainerList[0].canBeChanged());
			} else {
				MultiImageInformationWindow iw = new MultiImageInformationWindow(window, imageContainerList);
				iw.open(false);
			}
			
			// Append the images to the index
			RootIndexCategory ic = window.getCategoryPart().getRootIndexCategory();		
			for (int i=0; i<imageList.size(); i++) {
				ic.categorizeImage(imageContainerList[i], false);
			}
			ic.resortAll();
			
			// Refresh the picture list information
			window.refreshListPart();
		
			// Refresh the categorization viewer
			window.refreshCategoryPart();

			// Save the index
			ic.writeIndex();
			
		} catch (Exception e) {
			System.out.println (e);
		}

	}
	
}
